<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/28/0028
 * Time: 11:44
 */

namespace app\sports_admin\service;

use app\exception\AdminRuleException;
use app\sports_admin\model\Admin as AdminModel;
use app\sports_admin\model\AdminRule;
use think\Db;
use think\Request;
use app\exception\AdminException;
use think\Session;

class Admin
{
    /**
     * 添加管理员基本信息
     * @param $name 管理员姓名
     * @param $login 管理员账号
     * @param $password 管理员密码
     * @param $rule 管理员权限(权限管理表id)
     */
    public static function adminInsert()
    {
        $params = Request::instance()->only(['name','login','password','rule']);
        $bool = AdminModel::findAdmin($params['login']);
        if($bool){
            throw new AdminException([
                'msg'=>'管理员已存在',
                'errorCode'=>100
            ]);
        }
        Db::startTrans();
        $admin = AdminModel::create([
            'name'=>trim($params['name']),
            'login'=>trim($params['login']),
            'pwd'=>authcode(trim($params['password']),'ENCODE',trim($params['login']),0)
        ]);
        if(!$admin->id){
            Db::rollback();
            throw new AdminException([
                'msg'=>'管理员信息添加失败',
                'errorCode'=>400
            ]);
        }
        $adminRuleId = self::adminRuleInsert($params['rule'],$admin->id);
        if(!$adminRuleId){
            Db::rollback();
            throw new AdminRuleException([
                'msg'=>'管理员权限添加失败',
                'errorCode'=>400
            ]);
        }
        Db::commit();
        return true;
    }
    /**
     * 权限关联表添加信息
     * @param $ruleId 权限id
     * @param $adminId 管理员id
     */
    public static function adminRuleInsert($ruleId,$adminId)
    {
        $adminRule = AdminRule::create([
            'admin_id'=>$adminId,
            'rule_id'=>$ruleId
        ]);
        return $adminRule->id;
    }
    /**
     * 修改密码
     * @param $pass 原密码
     * @param $password 新密码
    */
    public static function updatePass()
    {
        $params = Request::instance()->only(['pass','password']);
        if(authcode(Session::get('sport_admin.login'),'DECODE',Session::get('sport_admin.pwd'),0) == trim($params['password'])){
            throw new AdminException([
                'msg'=>'原密码不能和新密码一致',
                'code'=>400
            ]);
        }
        $input['pwd'] = authcode(trim($params['password']),'ENCODE',Session::get('sport_admin.login'),0);
        $bool = AdminModel::where('id',Session::get('sport_admin.id'))->update($input);
        if(!$bool){
            throw new AdminException([
                'msg'=>'密码修改失败',
                'code'=>400
            ]);
        }
        return json(['code'=>201,'msg'=>'密码修改成功,请重新登录']);
    }
}